﻿// //文档就绪函数
$(function () {
    show();
})
var totalCount = 0;
var pageIndex = 1;
var pageSize = 100;

//采购显示
function show() {
    layui.use('table', function () {
        // var form = layui.form;
        var table = layui.table;
        //查询
        var returnNo = $("#returnNo").val();
        var procurementNo = $("#procurementNo").val();
        var productName = $("#productName").val();
        $.ajax({
            url: "/Purchase/GetReturnShow",
            type: "get",
            data: {
                returnNo: returnNo,
                procurementNo: procurementNo,
                productName: productName,
                pageIndex: pageIndex,
                pageSize: pageSize,
                token: localStorage.getItem("token"),
            },
            success: function (res) {
                var res = JSON.parse(res);
                if (res.code === 0) {
                    console.log(res.data.list)
                    table.render({
                        elem: returnsData,//对应HTML中表格的id
                        data: res.data.list,//绑定获取的数据
                        toolbar: '#toolbarDemo',//导出
                        defaultToolbar: ['exports'],//导出
                        cols: [[
                            { type: 'checkbox', fixed: 'left' },
                            { field: 'returnNo', title: '退货单号', width: 140 },
                            { field: 'productName', title: '产品名称', width: 150 },
                            { field: 'productNo', title: '产品编号', width: 110 },
                            { field: 'productSpec', title: '产品规格', width: 110 },
                            { field: 'unitName', title: '单位', width: 110 },
                            { field: 'price', title: '单价', width: 110 },
                            { field: 'returnsNum', title: '退货数', width: 110 },
                            {
                                field: 'productsTotal', title: '总额', templet: function (d) {
                                    return d.returnsNum  * d.price;
                                }, width: 170
                            },
                            { field: 'procurementNo', title: '采购单号', width: 140 },
                            { field: 'vendorName', title: '供应商名称', width: 110 },
                            { field: 'procurementStateText', title: '状态', width: 120 },
                            {
                                field: 'updateTime', title: '创建时间', templet: function (d) {
                                    return formatTime(d.updateTime);
                                }, width: 170
                            },
                            {
                                field: '', title: '操作', templet: function (d) {
                                    return '<a class="layui-btn layui-btn-edit layui-btn-xs" lay-on="test-page-edit" onclick="returnsmodel(' + d.procurementId + ')"><i class="layui-icon layui-icon-search"></i>查看</a> ' +
                                        '<a class="layui-btn layui-btn-danger layui-btn-xs" onclick="deleteData(' + d.buyProductsId + ')"><i class="layui-icon layui-icon-delete"></i>删除</a>';
                                }
                            }
                        ]],
                        page: true, // 是否显示分页
                        count: totalCount,
                        limits: [6, 9, 14],
                        limit: 6,// 每页默认显示的数量
                        curr: pageIndex,
                    })
                } else {
                    console.log(res.msg);
                }
            },
            error: function () {
                console.log("获取数据失败");
                // 可以考虑显示一个错误消息给用户
            }
        });
    });
    // 查看详情
    window.returnsmodel = function (procurementId) {
        // 先根据id获取要编辑的数据，发起Ajax请求
        $.ajax({
            type: "get",
            url: "/Purchase/GetFanReturn",  // 替换为实际的后台根据id获取数据的接口地址
            data: {
                procurementId: procurementId,
                token: localStorage.getItem("token")
            },
            success: function (res) {
                try {
                    const { data } = JSON.parse(res);
                    //console.log(data)
                    if (data) {
                        const { buyProductsData } = data;
                        var procurement = data;
                        console.log(procurement);
                        console.log(buyProductsData);
                        // 反填表单的函数
                        fillForm(procurement);
                        $('#procurementStateText').val(buyProductsData.procurementStateText);
                        //渲染表格的函数
                        //renderTable(buyProductsData);
                        layui.use('table', function () {
                            var table = layui.table;
                            if (buyProductsData) {
                                var inst = table.render({
                                    elem: '#returnProduct', // 对应HTML中表格的id
                                    data: buyProductsData, // 绑定获取的数据
                                    cols: [[
                                        { field: 'productNo', title: '产品编码' },
                                        { field: 'productName', title: '产品名称' },
                                        { field: 'productSpec', title: '规格' },
                                        { field: 'unitName', title: '单位' },
                                        { field: 'buyProductsNum', title: '数量' },
                                        { field: 'batch', title: '批次' },
                                        { field: 'returnsNum', title: '退货数' },
                                        { field: 'price', title: '单价' },
                                        {
                                            field: 'productsTotal', title: '总额', templet: function (d) {
                                                return d.returnsNum * d.price;
                                            }, width: 170
                                        },
                                    ]],
                                });
                            }
                        });
                        resolve(procurement, buyProductsData);
                    } else {
                        layui.layer.msg(res.message, { icon: 2 });
                        reject(res.message);
                    }
                } catch (e) {
                    //console.error(e);
                    //layui.layer.msg('数据解析失败，请稍后重试', { icon: 2 });
                    //reject('数据解析失败');
                }
            },
        });

        layer.open({
            type: 1,
            title: '采购单详情',
            content: `
                      <form class="layui-form" action="/CreateWarehouse">
    <div class="layui-form-item" style="margin-left:150px;margin-top:50px">
        <div class="layui-inline">
            <label class="layui-form-label">退货单号</label>
            <div class="layui-input-inline">
                <input type="text" name="returnNo" id="returnNo" lay-verify="required" autocomplete="off" placeholder="可不填写，自动生成" class="layui-input">
            </div>
        </div>
        <div class="layui-inline">
            <label class="layui-form-label">单据类型</label>
            <div class="layui-input-inline">
                <input type="text" name="procurementTypeName" id="procurementTypeName" autocomplete="off" class="layui-input">
            </div>
        </div>
        <div class="layui-inline">
            <label class="layui-form-label">单据状态</label>
            <div class="layui-input-inline">
                <input type="text" id="procurementStateText" name="procurementStateText" autocomplete="off" class="layui-input">
            </div>
        </div>
    </div>

    <div class="layui-form-item" style="margin-left:150px;margin-top:50px">
    <div class="layui-inline">
            <label class="layui-form-label">采购单号</label>
            <div class="layui-input-inline">
                <input type="text" name="procurementNos" id="procurementNos" lay-verify="required" autocomplete="off" placeholder="可不填写，自动生成" class="layui-input">
            </div>
        </div>
        <div class="layui-inline">
            <label class="layui-form-label">制单人</label>
            <div class="layui-input-inline">
                <input type="text" name="singleMaker" id="singleMaker" lay-verify="required" autocomplete="off" class="layui-input">
            </div>
        </div>
        <div class="layui-inline">
            <label class="layui-form-label">制单日期</label>
            <div class="layui-input-inline">
            <input type="text" name="singleTime" id="singleTime" lay-verify="required" autocomplete="off" class="layui-input">
            </div>
        </div>
    </div>

    <div class="layui-form-item" style="margin-left:150px;margin-top:50px">
    <div class="layui-inline">
            <label class="layui-form-label">联系人</label>
            <div class="layui-input-inline">
                <input type="text" name="procurementPerson" id="procurementPerson" lay-verify="required" autocomplete="off" class="layui-input">
            </div>
        </div>
    <div class="layui-inline">
            <label class="layui-form-label">供应商编号</label>
            <div class="layui-input-inline">
                <input type="text" id="vendorNo" name="vendorNo" autocomplete="off" class="layui-input">
            </div>
        </div>
        <div class="layui-inline">
            <label class="layui-form-label">供应商名称</label>
            <div class="layui-input-inline">
                <input type="text" id="vendorName" name="vendorName" autocomplete="off" class="layui-input">
            </div>
        </div>
    </div>

    <div class="layui-form-item" style="margin-left:150px;margin-top:50px">
        <div class="layui-inline">
            <label class="layui-form-label">电话</label>
            <div class="layui-input-inline">
                <input type="text" name="procurementPhone" id="procurementPhone" lay-verify="required" autocomplete="off" class="layui-input">
            </div>
        </div>
        <div class="layui-inline">
            <label class="layui-form-label">备注</label>
            <div class="layui-input-inline">
                <input type="text" name="procurementRemark" id="procurementRemark" autocomplete="off" class="layui-input" lay-verify="required">
            </div>
        </div>
    </div>
    
    <table class="layui-hide" id="returnProduct" lay-filter="test"></table>
</form>

`,
            area: ['1400px', '800px'],
            success: function () {

                // 对弹层中的表单进行初始化渲染
                //form.render();
            }
        });
    };
    var obj = {
        procurementId: 0,
        clientName: '',
        procurementState: '',
        isRecorded: '',
        isReturn: '',
    };
    // 反填表单的函数
    function fillForm(procurement) {

        $('#procurementNos').val(procurement.procurementNo);
        $('#procurementTypeName').val(procurement.procurementTypeName);

        $('#associateNumber').val(procurement.associateNumber);
        $('#vendorNo').val(procurement.vendorNo);
        $('#vendorName').val(procurement.vendorName);
        $('#clientName').val(procurement.clientName);
        $('#procurementPerson').val(procurement.procurementPerson);
        $('#procurementPhone').val(procurement.procurementPhone);
        $('#procurementRemark').val(procurement.procurementRemark);
        $('#singleMaker').val(procurement.singleMaker);

        //const hourss = ("0" + dates.getHours()).slice(-2);
        //const minutess = ("0" + dates.getMinutes()).slice(-2);
        const date = new Date(procurement.singleTime);
        const year = date.getFullYear();
        const month = ("0" + (date.getMonth() + 1)).slice(-2);
        const day = ("0" + date.getDate()).slice(-2);
        $('#singleTime').val(year + "-" + month + "-" + day);
        const dates = new Date(procurement.harvestay);
        const years = date.getFullYear();
        const months = ("0" + (date.getMonth() + 1)).slice(-2);
        const days = ("0" + date.getDate()).slice(-2);
        $('#harvestay').val(years + "-" + months + "-" + days);
        obj.procurementId = procurement.procurementId
        obj.clientName = procurement.clientName
        obj.procurementState = procurement.procurementState
        obj.isRecorded = procurement.isRecorded
        obj.isReturn = procurement.isReturn
        console.log(obj)
        console.log(procurement)
        // 重新渲染表单元素（如果有）
        //form.render();
    }

}

// 定义删除数据的函数（此处简单示意，可参考之前详细的删除功能代码完善）
window.deleteData = function (buyProductsId) {
    console.log(buyProductsId)
    layer.confirm('确定要删除该条数据吗？', function (index) {
        $.ajax({
            type: "Post",
            url: "/Purchase/GetDelectReturn",  // 替换为实际的后台删除数据接口地址
            data: {
                data: JSON.stringify({ buyProductsId: buyProductsId }),
                token: localStorage.getItem("token")
            },
            success: function (res) {
                var res = JSON.parse(res)
                if (res.code === 1) {
                    layer.alert("删除成功");
                    show();  // 重新加载数据，刷新表格显示
                } else {
                    layer.alert("删除失败");

                }
            },
            error: function () {
                layer.msg('删除失败，请稍后重试', {
                    time: 2000,
                    icon: 2
                });
            }
        });
        layer.close(index);
    });
};

// 点击批量删除按钮的事件处理
$('#batchDeleteBtn').click(function () {
    var table = layui.table;
    // 获取选中行的数据（这里主要是获取warehouseId）
    var checkStatus = table.checkStatus('returnsData');
    var selectedData = checkStatus.data.map(function (item) {
        return item.buyProductsId;
    });
    if (selectedData.length === 0) {
        layer.msg("请至少选择一条要删除的数据", { icon: 2 });
        return;
    }

    console.log(selectedData);
    layer.confirm('确定要批量删除选中的' + selectedData.length + '条数据吗？', function (index) {
        var buyProductsIds = {
            buyProductsId: selectedData
        }
        // 发送批量删除请求到后端
        $.ajax({
            url: "/Purchase/GetDelectRangeReturn", // 后端处理批量删除的接口地址，需根据实际情况调整
            type: "post",
            // contentType: "application/json",
            data: {
                buyProductsId: buyProductsIds,
                token: localStorage.getItem("token"),
            },
            success: function (res) {
                var res = JSON.parse(res)
                console.log(res.code);
                if (res.code > 0) {
                    layer.msg("批量删除成功", { icon: 1 })
                    // 重新加载表格数据，展示更新后的列表
                    show();
                } else {
                    layer.msg("批量删除失败:" + res.message, { icon: 2 });
                }
            },
            error: function () {
                console.log("批量删除数据失败");
                // 可以考虑显示一个错误消息给用户
            }
        });
    })
})

// 定义时间格式转换函数
function formatTime(timeStamp) {
    if (timeStamp) {
        var date = new Date(timeStamp);
        var year = date.getFullYear(); // 获取年份
        var month = ('0' + (date.getMonth() + 1)).slice(-2); // 获取月份，+1是因为getMonth()返回的月份是从0开始计数的
        var day = ('0' + date.getDate()).slice(-2); // 获取日期
        var hour = ('0' + date.getHours()).slice(-2); // 获取小时
        var minute = ('0' + date.getMinutes()).slice(-2); // 获取分钟
        var second = ('0' + date.getSeconds()).slice(-2); // 获取秒
        return year + '-' + month + '-' + day + ' ' + hour + ':' + minute + ':' + second;
    }
    return "";
}